package com.intelligentmeterreadingsys.waterbanding.activity;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.rfid.RfidHelper;
import com.baidu.location.LocationClientOption;
import com.intelligentmeterreadingsys.R;
import com.intelligentmeterreadingsys.httpserver.HttpClientServer;
import com.intelligentmeterreadingsys.httpserver.RequestUrl;
import com.intelligentmeterreadingsys.povo.UserWaterVO;
import com.intelligentmeterreadingsys.util.BaiDuGpsUtil;
import com.intelligentmeterreadingsys.util.BluetoothHelp;
import com.intelligentmeterreadingsys.util.SharedPreferenceUtil;
import com.intelligentmeterreadingsys.util.TipHelper;
import com.intelligentmeterreadingsys.waterbanding.db.WaterBandingImpl;
import com.intelligentmeterreadingsys.waterlist.copywater.db.CopyWaterDao;

import dbhelper.DbTableName;
import dbhelper.XmlNameHelper;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 水表绑定
 * @author king
 *
 */
public class WaterBandingActivity extends Activity implements OnClickListener{
	
	public Button button1;//读卡按钮
	
	public Button button2;//定位按钮
	
	public Button button3;//提交按钮
	
	public Button button6;//上传按钮
	
	
	public TextView textview1;//用户姓名
	
	public TextView textview4;//水表编号
	public TextView textview5;//水表地址
	public TextView textview6;//水表径度
	public TextView textview7;//水表维度
	public TextView textview8;//RFID卡号
	public EditText edit;
	public UserWaterVO list;
	public int i=0;
    private final static int DIALOG=1;		 
    public int FRIDtype=2;//RFID协议   
    public String xieyi="15693";
	public long time;	
	public String RFID;	
	public Double latitude=0.0;//维度	
	public Double longitude=0.0;//径度	
	public ProgressDialog pd;	
	public String imsi="";	
    public RfidHelper rh;//读卡帮助对象
	public boolean issave=false;
    public static final int ITEM0=Menu.FIRST;//系统值
	public boolean isStop=true;
	public boolean isupload=false;
	public WaterBandingMainActivity act=null;//父类
	public String readtype="终端读卡";
	
	public BluetoothHelp bluehelp;
	public String[] readdate;
	public boolean isbluetooth=true;
	public String[] date=null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.waterbanding);
		bluehelp=new BluetoothHelp(this);
		bluehelp.init();
		init();
		addDate();
		
	}

	/**
	 * 初始化组件
	 */
	public void init(){
		textview1=(TextView)findViewById(R.id.waterbanding_username);
	    edit=(EditText)findViewById(R.id.waterbanding_locationadds);
		textview4=(TextView)findViewById(R.id.waterbanding_waternumber);
	    textview5=(TextView)findViewById(R.id.waterbanding_wateradds);
		textview6=(TextView)findViewById(R.id.waterbanding_latitude);
		textview7=(TextView)findViewById(R.id.waterbanding_longitude);
		textview8=(TextView)findViewById(R.id.waterbanding_RFID);
		button1=(Button)findViewById(R.id.waterbanding_readcard);
		button2=(Button)findViewById(R.id.waterbanding_location);
		button3=(Button)findViewById(R.id.waterbanding_button);
	
		button6=(Button)findViewById(R.id.waterbanding_upload);
		button6.setOnClickListener(this);
	    button1.setOnClickListener(this);
		button3.setOnClickListener(this);
		
		rh=RfidHelper.getInstance();
		rh.setCardType(2);
		rh.open();
		rh.setAllNoOfTimes(1);
		rh.setTimeInterval(50);
		// 设置激活读卡器后等待的时间.sdk默认10
		rh.setPingTimeInterval(10);
		
		WaterBandingImpl dao=new WaterBandingImpl(this);
	
		  act=(WaterBandingMainActivity)getParent();
		this.list=dao.queryWaterInfo(act.getWaterid());
		
		addDate();
	    isStop=false;
	   
		dao.close();
		SharedPreferenceUtil sp=new SharedPreferenceUtil(this);
		imsi=sp.getValue(XmlNameHelper.IMSI);
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.waterbanding_readcard:
			

			Date d=new Date();
			time=d.getTime();
			pd=new ProgressDialog(this);
			pd.setMessage("扫描中.....");
			pd.show();
			RFID="";
			if(!readtype.equals("终端读卡")){				
				 bluehelp.start();
				 pd.dismiss();
			}
			isStop=true;
			
			new Thread(){

				@Override
				public void run() {
				   while(isStop){
					   Date d=new Date();
					   if(d.getTime()-time>20000){
						   isStop=false;
						   Message msg=MyHandler.obtainMessage();
						   msg.what=2;
						   MyHandler.sendMessage(msg);
					   }
					  
					   String id="";
					   if(readtype.equals("终端读卡")){
						    id=rh.readIDString();
					   }else{
						  		 
						   id=bluehelp.getRfidId(); 
					   }
					   if(!TextUtils.isEmpty(id)){
						   isStop=false;
						  Message msg=MyHandler.obtainMessage();
						  msg.what=1;
						  msg.obj=id;
						  MyHandler.sendMessage(msg);
					   }
					   try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
				
						e.printStackTrace();
					}
				   }
					super.run();
				}
				
			}.start();
			break;
		
		case R.id.waterbanding_button:
			if(list==null){
				Toast.makeText(WaterBandingActivity.this, "没水表不能绑定", 1000).show();
				return;
			}
			if(RFID==null||RFID.equals("")){
				Toast.makeText(WaterBandingActivity.this, "没有读卡不能绑定", Toast.LENGTH_SHORT).show();
				return;
			}
			banding();
			break;
		case R.id.waterbanding_location:
			
			break;
		case R.id.waterbanding_upload:
			WaterBandingImpl dao=new WaterBandingImpl(this);
			
			  act=(WaterBandingMainActivity)getParent();
			this.list=dao.queryWaterInfo(act.getWaterid());
			if(issave){
			    pd=new ProgressDialog(WaterBandingActivity.this);
				pd.setMessage("上传中....");
				pd.show();
				final HttpClientServer server=new HttpClientServer(this);
				new Thread(){

					@Override
					public void run() {
						
						Map<String, String> map=new HashMap<String, String>();
						map.put("waternumber", textview4.getText().toString());
						map.put("latitude", latitude+"");
						map.put("longitude", longitude+"");
						map.put("RFIDnumber", textview8.getText().toString());
						map.put("addr", list.getAdds());
						map.put("imsi",imsi);
						
					String respone=	server.doPost(map, RequestUrl.BandingWater);
					System.out.println(respone);
					   if(respone.equals("error")){
						   Message msg=handle.obtainMessage();
						   msg.what=1;
						   handle.sendMessage(msg);
					   }else {
						  try {
							JSONObject json=new JSONObject(respone);
							String message=json.getString("message");
							if(message.equals("yes")){
								Message msg=handle.obtainMessage();
								msg.what=2;
								handle.sendMessage(msg);
							}else{
								Message msg=handle.obtainMessage();
								msg.what=3;
								handle.sendMessage(msg);
							}
						} catch (JSONException e) {
							Message msg=handle.obtainMessage();
							msg.what=3;
							handle.sendMessage(msg);
						}
						   
					   }
					}
					
				}.start();
			}
			
			
			break;
		default:
			break;
		}
		
	}
	
 /**
  * 添加数据
  */
	public void addDate(){
		textview1.setText("");
	    edit.setText("");
		textview4.setText("");
		textview5.setText("");
		textview6.setText("纬度:");
		textview7.setText("经度:");
		textview8.setText("");
		this.RFID="";
		this.latitude=0.0;
		this.longitude=0.0;
		if(list!=null){
			UserWaterVO water=list;
			textview1.setText(water.getName());
			System.out.println(water.getAdds()+"----------------");
			edit.setText(water.getAdds());
			textview4.setText(water.getWaternumber());
			textview5.setText(water.getWateradds());
			textview6.setText("纬度:"+water.getLatitude()+"");
			textview7.setText("经度:"+water.getLongitude()+"");
			textview8.setText(water.getRFIDnumber());
			this.RFID=water.getRFIDnumber();
			this.latitude=water.getLatitude();
			this.longitude=water.getLongitude();
		}
	}
	
	
	/**
	 * 绑定、修改（定位，RFID卡）
	 */
	public void banding(){
		WaterBandingImpl dao=new WaterBandingImpl(this);
		String waternumber=textview4.getText().toString().trim();
		
		if(TextUtils.isEmpty(waternumber)){
			Toast.makeText(WaterBandingActivity.this, "没有水表编号不能进行此操作", Toast.LENGTH_LONG).show();
			return;
			
		}
	
		boolean b=dao.BandingRFID(list.getWaterid(), RFID, latitude, longitude,edit.getEditableText().toString());
		if(b){
			Toast.makeText(WaterBandingActivity.this, "操作成功", Toast.LENGTH_LONG).show();
		     this.list= dao.queryWaterInfo(act.getWaterid());
			
		     issave=true;
		}else{
			Toast.makeText(WaterBandingActivity.this, "操作失败", Toast.LENGTH_LONG).show();
		}
		addDate();
		dao.close();
	}
	
	
	@Override
	protected void onDestroy() {
		
		this.i=0;
		 if(rh != null){
				rh.stopAutoRead();
			    rh.close();
			}
	   if(bluehelp!=null){
		   bluehelp.stop();
	   }
		super.onDestroy();
	}


	 public	Handler MyHandler=new Handler(){

			@Override
			public void handleMessage(Message msg) {
			       if(msg.what==1){
			    	   isStop=false;
			    	   pd.dismiss();
			    	  
			    	   TipHelper.Vibrate(WaterBandingActivity.this, 1000);
			    	   textview8.setText(msg.obj.toString());
			    	   WaterBandingImpl dao=new WaterBandingImpl(WaterBandingActivity.this);
			    	   
			    	    UserWaterVO user= dao.queryUserWater(msg.obj.toString());
			    	   
			    	    dao.close();
			    	    if(readtype.equals("蓝牙读卡")){
			    	    	bluehelp.close();
			    	    }
			    	if(user!=null){
			    		Toast.makeText(WaterBandingActivity.this, "此RFID已绑定了水表", 1000).show();
			    		list=user;
			    		 act.setWaterid(user.getWaterid());
			    		addDate();
			    	}else{
			    		Toast.makeText(WaterBandingActivity.this, "此RFID卡还未绑定水表", 1000).show();
			    		
			    	}
			    
			    	   RFID=msg.obj.toString();
			    	   
			    	   
			       }else{
			    	   isStop=false;
			    	   Toast.makeText(WaterBandingActivity.this, "读卡超时", 1000).show();
			    	   if(readtype.equals("蓝牙读卡")){
			    		   bluehelp.close();
			    	   }
			    	   pd.dismiss();
			       }
			}
			
		};



	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		menu.add(0, ITEM0, 0, "短息通知");
		menu.add(0,ITEM0+1,0,"RFID协议");
	
		menu.add(0,ITEM0+3,0,"读卡方式");
		menu.findItem(ITEM0+1);
		return true;
		
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId()==ITEM0){
			if(list==null){
				Toast.makeText(WaterBandingActivity.this, "没查到用户无法发送", Toast.LENGTH_LONG).show();
				return false;
			}
			Uri smsToUri = Uri.parse("smsto:"); 
		     Intent sendIntent = new Intent(Intent.ACTION_VIEW, smsToUri); 
		      sendIntent.putExtra("address", list.getPhone());   //电话号码，这行去掉的话，默认就没有电话
		     sendIntent.putExtra("sms_body","尊敬的"+list.getName()+"用户:你的水表已绑定RFID卡"); 
		     sendIntent.setType("vnd.android-dir/mms-sms"); 
		     startActivity(sendIntent);
			System.out.println("发短息");
		}else if(item.getItemId()==(ITEM0+1)){
			showDialog(DIALOG);
			System.out.println("选择协议");
		}else if(item.getItemId()==(ITEM0+2)){
			
			showDialog(DIALOG+1);
		}else if(item.getItemId()==(ITEM0+3)){
			showDialog(DIALOG+2);
		}
		return super.onOptionsItemSelected(item);
	}

	
	@Override
	protected Dialog onCreateDialog(int id) {

		 Dialog dialog=null;
	        switch (id) {
	        case DIALOG:
	            Builder builder=new android.app.AlertDialog.Builder(this);
	            //设置对话框的图标
	            builder.setIcon(R.drawable.buttondraw);
	            //设置对话框的标题
	            builder.setTitle("单选按钮对话框");
	            //0: 默认第一个单选按钮被选中
	            
	            builder.setSingleChoiceItems(R.array.hobby, 0, new android.content.DialogInterface.OnClickListener(){
	                public void onClick(DialogInterface dialog, int which) {
	                   xieyi=getResources().getStringArray(R.array.hobby)[which];
	                   
	                }
	            });
	            
	            //添加一个确定按钮
	            builder.setPositiveButton(" 确 定 ", new DialogInterface.OnClickListener(){
	                public void onClick(DialogInterface dialog, int which) {
	                    if(xieyi.equals("15693")){
	                    	initRFID(2);
	                    	time=System.currentTimeMillis();
	                    }else if(xieyi.equals("14443")){
	                    	time=System.currentTimeMillis();
	                    	initRFID(1);
	                    }
	                }
	            });
	            //创建一个单选按钮对话框
	            dialog=builder.create();
	            break;
	        
            
	        case DIALOG+2:
	        	if(readtype.equals("终端读卡")){
	        		readdate=new String[]{"终端读卡","蓝牙读卡"};
	        	}else{
	        		readdate=new String[]{"蓝牙读卡","终端读卡"};
	        	}
	        	
	            builder=new android.app.AlertDialog.Builder(this);
	            //设置对话框的图标
	            builder.setIcon(R.drawable.buttondraw);
	            //设置对话框的标题
	            builder.setTitle("读卡方式选择");
	            //0: 默认第一个单选按钮被选中
	            
	            builder.setSingleChoiceItems(readdate, 0, new android.content.DialogInterface.OnClickListener(){
	                public void onClick(DialogInterface dialog, int which) {
	                   readtype=readdate[which];
	                   
	                }
	            });
	            
	            //添加一个确定按钮
	            builder.setPositiveButton(" 确 定 ", new DialogInterface.OnClickListener(){
	                public void onClick(DialogInterface dialog, int which) {
	                	time=System.currentTimeMillis();
	                }
	            });
	            //创建一个单选按钮对话框
	            dialog=builder.create();
	            break;
	        }
	        return dialog;
	}	
	
	/**
	 * 初始化读卡
	 */
	public void initRFID(int type){
		rh=RfidHelper.getInstance();
		rh.setCardType(type);
		rh.open();
		rh.setAllNoOfTimes(1);
		rh.setTimeInterval(50);
		// 设置激活读卡器后等待的时间.sdk默认10
		rh.setPingTimeInterval(10);
	}
	
	Handler handle=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			pd.dismiss();
			if(msg.what==1){
				Toast.makeText(WaterBandingActivity.this, "网络错误", Toast.LENGTH_LONG).show();
			}else if(msg.what==2){
				Toast.makeText(WaterBandingActivity.this, "上传成功", Toast.LENGTH_LONG).show();
				WaterBandingImpl dao=new WaterBandingImpl(WaterBandingActivity.this);
				ContentValues values=new ContentValues();
				values.put("bandingstatus", "1");
				dao.modify(list.getWaterid(), DbTableName.WATERINFO, values);
				dao.close();
				isupload=true;
			}else if(msg.what==3){
				Toast.makeText(WaterBandingActivity.this, "上传失败", Toast.LENGTH_LONG).show();
			}
		}
		
	};

	/**
	 * 得到水表数据
	 */
public void queryWater(){
	i=0;
	WaterBandingImpl dao=new WaterBandingImpl(this);		
	act=(WaterBandingMainActivity)getParent();
	this.list=dao.queryWaterInfo(act.getWaterid());		
	addDate();	
	dao.close();
}
	
	
}
